Enumeration
An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.
Syntax
A enumeration is introduced by enum
declarator:
EnumerationName: enum = {
};
Enumerators are a list of identifiers separated by commas:
ExtensionState: enum = {
Empty,
Unloaded,
Ready, //extra trailing comma is allowed
}
You can define a enumeration instance that stores an enumerator:
foo: ExtensionState = ExtensionState.Empty;
//the type can be omitted:
foo := ExtensionState.Empty;
Once the type of a enumeration instance is known, the enumerator's enumeration can be omitted:
foo mutable := ExtensionState.Empty;
foo = .Ready;
Raw Values
An enumerator can have a raw value to represent itself. If no raw value is provided, the identifier string will be the enumerator's default raw value. You can provide raw value for a enumerator by adding := value
to the identifier:
ExtensionState: enum = {
Empty := true,
Unloaded := 1::Int32,
Loading,
Ready := "ready_state",
}
You can create enumeration instances by their raw values:
foo := ExtensionState.init(rawValue = true);
//equals to:
foo := ExtensionState.Empty;
If the arguments of enumeration's raw value constructor are not compile-time known, the constructor may throw an std.user.exception.Enumeration.InvalidRawValue(rawValue: ValueType)
exception, so you need to use try
to initialize them.
foo := try ExtensionState.init(rawValue = bar) catch {
println("Invalid argument exception.rawValue$ for enumeration ExtensionState!");
};
foo := try? ExtensionState.init(rawValue = bar);
foo := try! ExtensionState.init(rawValue = bar);
Associated Values
Enumerators can have associated values of any given type. Associated values are particularly useful when the enumerator can't carry enough needed information by itself. Using associated values enables us to store and pass values alongside the enumerator.
To make enumerators have associated values, a list should be provided after the colon :
ExtensionState: enum = {
Empty,
Unloaded,
Loading: (path: filesystem.Path),
Ready: (instance: Extension, uuid: utils.UUID)
}
Then you can create enumeration instances with associated value provided:
foo := ExtensionState.Ready(instance = bar, uuid = bar.uuid);